import 'package:shared_preferences/shared_preferences.dart';

import '../constants/index.dart';

class TokenManager {
  String? _token;
  String? _refreshToken;

  //实例化持久化对象
  Future<SharedPreferences> _getInstance() async {
    final SharedPreferences pre = await SharedPreferences.getInstance();
    return pre;
  }

  //写入持久化
  Future<void> setPre(String token, {String? refreshToken}) async {
    final SharedPreferences pre = await _getInstance();
    //持久化token
    pre.setString(GlobalVariable.TOKEN, token);
    //将token赋值给变量
    _token = token;

    if (refreshToken != null) {
      pre.setString(GlobalVariable.REFRESH_TOKEN, refreshToken);
      _refreshToken = refreshToken;
    }
  }

  // Future<String> getPre() async {
  //   final SharedPreferences pre = await _getInstance();
  //   return pre.getString(GlobalVariable.TOKEN) ?? '';
  // }
  //初始化token 一进入项目必须初始化
  Future<void> initToken() async {
    final SharedPreferences pre = await _getInstance();
    _token = pre.getString(GlobalVariable.TOKEN);
    _refreshToken = pre.getString(GlobalVariable.REFRESH_TOKEN);
  }

  //获取token
  String getToken() {
    return _token ?? '';
  }

  String getRefrsshToken() {
    return _refreshToken ?? '';
  }

  //清空持久化
  Future<void> removePre() async {
    final SharedPreferences pre = await _getInstance();
    //清空持久化token
    pre.remove(GlobalVariable.TOKEN);
    //清空token
    _token = '';

    pre.remove(GlobalVariable.REFRESH_TOKEN);
    _refreshToken = '';
  }
}

final TokenManager tokenManager = TokenManager();
